package cz.cvut.fel.persister;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;

import org.apache.commons.io.FileUtils;

import cz.cvut.fel.email.Email;
import cz.cvut.fel.loader.Persister;

public class FileSystemPersister extends Persister implements Runnable {

	private String path;
	
	private BlockingQueue<byte[]> emailData = new LinkedBlockingQueue<byte[]>(100);
	
	/**
	 * @return the emailData
	 */
	public BlockingQueue<byte[]> getEmailData() {
		return emailData;
	}


	/**
	 * @param emailData the emailData to set
	 */
	public void setEmailData(BlockingQueue<byte[]> emailData) {
		this.emailData = emailData;
	}


	public FileSystemPersister(String path) {
		super(null,null);
		
		this.path = path;
	}
	

	@Override
	public byte[] readBytes() throws Exception {
		//return FileUtils.readFileToByteArray(new File(fileList.take()));
		return emailData.take();
	}
	
	public void run() {		
		storeEmail(path);
	}



	public void storeEmails() throws Exception {
//	persister.store(parser.parseEmail(ff.getPath()));
	}
	
	private void storeEmail(String path)  {
		File f = new File(path);
		if (f.isDirectory()) {
			for (int i = 0; i < f.listFiles().length; i++) {
				File ff = f.listFiles()[i];
				if (ff.isDirectory()) {
					storeEmail(ff.getPath());

				} else {
					if (!ff.getPath().contains(".envelope")) {
						try {
							emailData.put(FileUtils.readFileToByteArray(ff));
							//fileList.put(ff.getPath());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}


	@Override
	public void connect() throws Exception {
		; //nop
	}


	@Override
	public void disconnect() {
		; //nop
	}


	@Override
	public void store(Email email) throws Exception {
		throw new Exception("nop");
		
	}


	

}
